from subwin_template_ui import Ui_subwin_template
from PyQt6.QtWidgets import QMessageBox, QWidget
from threading import Thread
from img_server import template_text


class subwin_template(QWidget, Ui_subwin_template):
    def __init__(self, mainwin):
        super().__init__()
        self.mainwin = mainwin
        self.setupUi(self)
        self.initUi()

    def initUi(self):
        self.setFixedSize(343, 417)

        self.plainTextEdit.setPlainText(self.mainwin.img_obj.template)
        self.btn_submit.clicked.connect(self.handle_submit)
        self.btn_default.clicked.connect(self.handle_default)

    def handle_submit(self):
        template_raw = self.plainTextEdit.toPlainText().strip()
        if not template_raw:
            QMessageBox.warning(self, '有效内容为空', '你输入的有效内容为空, 请输入正确内容后再试')
            self.plainTextEdit.setPlainText(self.mainwin.img_obj.template)
            return
        
        if len(template_raw) > 250:
            
            btn=QMessageBox.warning(self,'内容过多','你输入的内容过多.\n\n是否恢复上次内容, 以供参考?\n- 点击Yes恢复上次内容\n- 点击No继续编辑原内容',QMessageBox.StandardButton.Yes|QMessageBox.StandardButton.No)
            if btn == QMessageBox.StandardButton.Yes:
                self.plainTextEdit.setPlainText(self.mainwin.img_obj.template)
            return
        
        try:
            # 防止format异常
            # 原本应该在img_server里检测
            template_raw.format(date='', dujing1='', dujing2='', daogao='')
        except Exception as e:
            btn = QMessageBox.warning(
                self, 'ValueError', f'你输入的内容有误, 错误信息如下:\n{e}\n\n是否恢复上次模板?\n- 点击Yes恢复上次模板\n- 点击No继续编辑原模板', QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
            if btn == QMessageBox.StandardButton.Yes:
                self.plainTextEdit.setPlainText(self.mainwin.img_obj.template)

            return

        if self.mainwin.img_obj.template == template_raw:
            # print('内容无变动, 不重新生成预览')
            self.close()
            # 必须return, 否则窗口关闭后继续运行
            return
        self.mainwin.img_obj.template = template_raw
        t = Thread(target=self.mainwin.handle_preview, args=('__temp__',))
        t.start()
        # print('已重新生成预览')
        self.close()

    def handle_default(self):
        self.plainTextEdit.setPlainText(template_text)
